<template>
  <px-scrollbar v-if="drawerType === 'execute'" height="calc(100vh - 500px)">
    <px-form ref="recordFormRef" :model="formValue" label-position="right" label-width="120px">
      <EditDropDown dropdownTitle="维修状况">
        <template v-slot:content>
          <px-row style="width: 100%">
            <px-col :span="24">
              <px-form-item label="故障现象" prop="faultPhenomenon">
                <px-input
                  v-model="formValue.faultPhenomenon"
                  style="width: 100%"
                  type="textarea"
                  placeholder="请输入故障现象"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  maxlength="1000"
                  clearable
                />
              </px-form-item>
            </px-col>
          </px-row>
          <px-row style="width: 100%">
            <px-col :span="24">
              <px-form-item label="故障原因" prop="faultCause">
                <px-input
                  v-model="formValue.faultCause"
                  type="textarea"
                  placeholder="请输入故障原因"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  maxlength="1000"
                  clearable
                />
              </px-form-item>
            </px-col>
          </px-row>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="维修记录">
        <template v-slot:content>
          <div style="width: 100%">
            <px-button type="primary" style="margin-bottom: 20px" plain icon="Plus" @click="handleAdd">添加维修记录</px-button>
            <px-form ref="maintenanceRecordRef" :model="recordForm">
              <px-table
                v-if="recordForm.maintenanceRecords && recordForm.maintenanceRecords.length !== 0"
                :data="recordForm.maintenanceRecords"
                border
              >
                <px-table-column fixed="left" type="index" width="60" label="序号" />
                <px-table-column fixed="left" prop="maintenanceItem" label="维护项目" min-width="160" show-overflow-tooltip>
                  <template #default="scope">
                    <template v-if="isEdit(scope.$index)">
                      <px-form-item
                        label-width="0px"
                        label=""
                        :prop="'maintenanceRecords.' + scope.$index + '.maintenanceItem'"
                        :rules="[{ required: true, message: '维护项目不能为空', trigger: 'blur' }]"
                      >
                        <px-input v-model="scope.row.maintenanceItem" placeholder="请输入维护项目" maxlength="50" clearable />
                      </px-form-item>
                    </template>
                    <template v-else>{{ scope.row.maintenanceItem }}</template>
                  </template>
                </px-table-column>
                <px-table-column fixed="left" prop="implementationRecord" label="维修实施记录" min-width="160" show-overflow-tooltip>
                  <template #default="scope">
                    <template v-if="isEdit(scope.$index)">
                      <px-form-item
                        label-width="0px"
                        label=""
                        :prop="'maintenanceRecords.' + scope.$index + '.implementationRecord'"
                        :rules="[{ required: true, message: '维修实施记录不能为空', trigger: ['blur', 'change'] }]"
                      >
                        <px-input v-model="scope.row.implementationRecord" placeholder="请输入维修实施记录" maxlength="50" clearable />
                      </px-form-item>
                    </template>
                    <template v-else>{{ scope.row.implementationRecord }}</template>
                  </template>
                </px-table-column>
                <px-table-column fixed="left" prop="recordTime" label="记录时间" min-width="160" show-overflow-tooltip>
                  <template #default="scope">
                    <template v-if="isEdit(scope.$index)">
                      <px-form-item label-width="0px" label="" prop="recordTime">
                        <px-date-picker
                          v-model="scope.row.recordTime"
                          format="YYYY-MM-DD HH:mm:ss"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          type="datetime"
                          placeholder="请选择日期"
                        />
                      </px-form-item>
                    </template>
                    <template v-else>{{ scope.row.recordTime }}</template>
                  </template>
                </px-table-column>
                <px-table-column>
                  <template #default="scope">
                    <px-tooltip v-if="isEdit(scope.$index)" content="添加" placement="top">
                      <px-button link icon="Check" type="primary" @click="handleCheck(scope.row)" />
                    </px-tooltip>
                    <px-tooltip v-else content="编辑" placement="top">
                      <px-button link icon="EditPen" type="primary" @click="handleEdit(scope.row, scope.$index)" />
                    </px-tooltip>
                    <px-tooltip v-if="isEdit(scope.$index)" content="取消" placement="top">
                      <px-button link icon="Close" type="primary" @click="handleCancel" />
                    </px-tooltip>
                    <px-tooltip v-else content="删除" placement="top">
                      <px-button link icon="Delete" type="primary" @click="handleDelete(scope.row)" />
                    </px-tooltip>
                  </template>
                </px-table-column>
              </px-table>
            </px-form>
          </div>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="图片">
        <template v-slot:content>
          <px-row>
            <px-col :span="24">
              <px-form-item prop="faultImageIds" label-width="0px">
                <PhotoUpload
                  :photoType="photoType"
                  :photoData="{ moduleName: moduleName }"
                  :photoList="formValue.files"
                  style="margin-bottom: 18px"
                  @changePhotoList="changePhotoList"
                  @savePhotoStatus="savePhotoStatus"
                />
              </px-form-item>
            </px-col>
          </px-row>
        </template>
      </EditDropDown>
    </px-form>
    <div class="info-form-btns">
      <px-button type="primary" :disabled="photoStatusFlag" @click="handleSubmit(recordFormRef)">保存进度</px-button>
      <px-button
        v-if="drawerType !== 'view' && [4, 6].includes(status) && userId === taskDetailData.executorId"
        type="primary"
        @click="emits('handleFinish')"
      >
        完成维修
      </px-button>
      <px-button @click="backMainPage">取消</px-button>
    </div>
  </px-scrollbar>
  <px-scrollbar v-else height="calc(100vh - 444px)">
    <div class="view-equip-title">维修状况</div>
    <div class="view-equip-wrap">
      <div class="view-equip-content">
        <div class="view-equip-item plus">
          <div class="label">故障现象</div>
          <div class="text">{{ taskDetailData.faultPhenomenon }}</div>
        </div>
      </div>
      <div class="view-equip-content">
        <div class="view-equip-item plus">
          <div class="label">故障原因</div>
          <div class="text">{{ taskDetailData.faultCause }}</div>
        </div>
      </div>
    </div>
    <p class="view-equip-title">维修记录</p>
    <px-table :data="taskDetailData.maintenanceRecords" class="equip-table" size="small" max-height="400" border>
      <px-table-column label="序号" type="index" width="55" align="center" />
      <px-table-column
        v-for="(item, index) in tableColumns"
        :key="index"
        :label="item.label"
        :min-width="item.minWidth"
        :show-overflow-tooltip="item.showOverflowTooltip"
      >
        <template #default="scope">{{
          scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
        }}</template>
      </px-table-column>
    </px-table>
    <p v-if="taskDetailData.files && taskDetailData.files.length !== 0" class="view-equip-title">图片</p>
    <PhotoUpload photoType="view" :photoData="{ moduleName }" :photoList="taskDetailData.files" />
    <div class="view-equip-title">执行信息</div>
    <div class="view-equip-wrap">
      <div class="view-equip-content">
        <div class="view-equip-item">
          <div class="label">执行人</div>
          <div class="text">{{ taskDetailData.executorName }}</div>
        </div>
        <div class="view-equip-item">
          <div class="label">接单时间</div>
          <div class="text">{{ taskDetailData.acceptTime }}</div>
        </div>
        <div class="view-equip-item">
          <div class="label">维修完成时间</div>
          <div class="text">{{ taskDetailData.completionTime }}</div>
        </div>
      </div>
      <div class="view-equip-content">
        <div class="view-equip-item">
          <div class="label">四级主管验收</div>
          <div class="text">{{ taskDetailData.isSupervised === 1 ? "需要验收" : taskDetailData.isSupervised === 0 ? "无需验收，仅通知" : "" }}</div>
        </div>
        <div class="view-equip-item large">
          <div class="label">四级主管</div>
          <div class="text">{{ taskDetailData.supervisorName }}</div>
        </div>
      </div>
    </div>
    <p v-if="taskDetailData.isSupervised === 1 && [5, 6, 8].includes(status)" class="view-equip-title">验收信息</p>
    <px-table
      v-if="taskDetailData.isSupervised === 1 && [5, 6, 8].includes(status)"
      :data="taskDetailData.approvalRecords"
      class="equip-table"
      size="small"
      min-height="200px"
      border
    >
      <px-table-column
        v-for="(item, index) in checkTableColumns"
        :key="index"
        :label="item.label"
        :min-width="item.minWidth"
        :show-overflow-tooltip="item.showOverflowTooltip"
      >
        <template #default="scope">{{
          scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
        }}</template>
      </px-table-column>
    </px-table>
  </px-scrollbar>
</template>
<script lang="ts" setup>
import {
  addMaintainRecordList,
  delMaintainRecordList,
  editMaintainRecordList,
  getMaintainRecordList,
  queryMaintenanceInfo,
  saveMaintenanceInfo
} from "@/api/equip/maintain";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getToken } from "@/utils/auth";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { reactive, ref, toRefs, watchEffect } from "vue";

// 调用父级-返回主页、查询列表
const emits = defineEmits(["backMainPage", "handleFinish"]);
// 父级传过来的值
const props = defineProps(["taskId", "activeName", "status", "drawerType", "userId"]);
const preName = defineModel("preName");
const recordFormRef = ref();
const maintenanceRecordRef = ref();
const state = reactive<any>({
  formValue: {},
  dialogImageUrl: "",
  editIndex: -1,
  imageVisible: false,
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  photoType: "add",
  moduleName: "",
  photoStatusFlag: false,
  maintenanceRecords: [],
  taskDetailData: {},
  restoreForm: "",
  restoreTable: "",
  recordForm: {
    maintenanceRecords: []
  }
});
const { formValue, editIndex, photoType, moduleName, photoStatusFlag, maintenanceRecords, taskDetailData, recordForm, restoreForm, restoreTable } =
  toRefs(state);

// 获取维修记录列表
const getRecordsList = async () => {
  const res = await getMaintainRecordList({ workOrderId: props.taskId });
  recordForm.value.maintenanceRecords = res || [];
};

// 获取维修结果
const getMaintenanceInfo = async () => {
  const res = await queryMaintenanceInfo({ workOrderId: props.taskId });
  const { files } = res;
  taskDetailData.value = { ...res, files: files || [] } || {};
  formValue.value = { ...res, files: files || [] } || {};
};

watchEffect(async () => {
  console.log("当前tab值", props.activeName);
  if (props.activeName === "second") {
    await getRecordsList();
    await getMaintenanceInfo();
    if (props.drawerType === "execute") {
      restoreForm.value = JSON.stringify(formValue.value);
      restoreTable.value = JSON.stringify(maintenanceRecords.value);
    }
  } else if (preName.value === "second") {
    console.log(preName.value);
    if (props.drawerType !== "execute") {
      preName.value = "";
      return;
    }
    if (restoreForm.value !== JSON.stringify(formValue.value) || restoreTable.value !== JSON.stringify(maintenanceRecords.value)) {
      PxMessageBox.confirm("切换页签会导致“维修结果”内容无法保存，确定要切换吗？", "提示", {
        confirmButtonText: "保存进度",
        cancelButtonText: "取消保存",
        type: "warning",
        draggable: true
      })
        .then(async () => {
          handleSubmit(recordFormRef);
          preName.value = "";
        })
        .catch(() => {
          preName.value = "";
        });
    } else {
      preName.value = "";
    }
  }
});

// 新的图片列表
const changePhotoList = val => {
  console.log(val);
  formValue.value.faultImageIds = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};

const isEdit = index => index === editIndex.value;

const handleAdd = () => {
  recordForm.value.maintenanceRecords.push({});
  editIndex.value = recordForm.value.maintenanceRecords.length - 1;
};

const handleCheck = async row => {
  if (row.id) {
    const res = await editMaintainRecordList({ workOrderId: props.taskId, ...row });
    if (res) {
      editIndex.value = -1;
      getRecordsList();
    }
  } else {
    const res = await addMaintainRecordList({ workOrderId: props.taskId, ...row });
    if (res) {
      editIndex.value = -1;
      getRecordsList();
    }
  }
};

const handleEdit = (row, index) => {
  editIndex.value = index;
};

const handleDelete = async row => {
  const res = await delMaintainRecordList({ ids: [row.id] });
  if (res) {
    editIndex.value = -1;
    PxMessage.success("删除成功");
    getRecordsList();
  }
};

const handleCancel = () => {
  editIndex.value = -1;
  recordForm.value.maintenanceRecords.pop();
};
// 返回主页面
const backMainPage = () => {
  PxMessageBox.confirm(`确认退出工单吗？退出后内容将不会保存，请谨慎操作`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      // const ids = recordForm.value.maintenanceRecords.map(item => item.id);
      // const res = await delMaintainRecordList({ ids });
      // if (res) {
      recordFormRef.value.resetFields();
      emits("backMainPage");
      // }
    })
    .catch(() => {});
};

const handleSubmit = async (formEl: any, type?: any) => {
  if (!formEl) return;
  const params = formValue.value;
  const faultImageIds = [];
  if (formValue.value.faultImageIds && formValue.value.faultImageIds.length > 0) {
    formValue.value.faultImageIds?.forEach(item => {
      if (item?.id) {
        faultImageIds.push(item.id);
      } else if (item?.response.data.id) {
        faultImageIds.push(item.response.data.id);
      }
    });
  }

  const res = await saveMaintenanceInfo({ workOrderId: props.taskId, ...params, faultImageIds });
  if (res) {
    restoreForm.value = JSON.stringify(formValue.value);
    restoreTable.value = JSON.stringify(maintenanceRecords.value);
    PxMessage.success("保存进度成功");
  }
};

const tableColumns = [
  { prop: "maintenanceItem", label: "维护项目", minWidth: "120", showOverflowTooltip: true },
  { prop: "recordTime", label: "记录时间", minWidth: "120", showOverflowTooltip: true },
  { prop: "implementationRecord", label: "维修实施记录", minWidth: "200", showOverflowTooltip: true }
];

const checkTableColumns = [
  { prop: "approverName", label: "验收人", minWidth: "120", showOverflowTooltip: true },
  { prop: "approvalTime", label: "验收时间", minWidth: "120", showOverflowTooltip: true },
  { prop: "approvalResultDesc", label: "验收结果", minWidth: "120", showOverflowTooltip: true },
  { prop: "approvalOpinion", label: "验收意见", minWidth: "200", showOverflowTooltip: true }
];
</script>
<style lang="scss" scoped>
@import url("./style.scss");

.title {
  height: 22px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: bold;
  line-height: 22px;
  color: rgb(0 0 0 / 80%);
}

:deep(.px-form-item) {
  padding-top: 16px;
}
</style>
